<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class BAMembershipCooker extends BAEventCooker {

    const Render_Display_UserInfo = 'displayUserInfo';
    const Render_Approve_Membership = 'approveMembership';
    const Render_Authenticate_User = 'displayAuthenticate';
    const Render_Authenticate_User_hamshun = 'displayAuthenticateHamshun';
    const Render_Modify_UserInfo = 'modifyUserInfo';

    /* 猫抓的相应页面 */
    const Render_MemberCard = 'member'; //会员卡的首页
    const Render_AccountBalance = 'accountBalance'; //账户余额
    const Render_MyPoint = 'myPoint';   //会员积分页面
    const Render_MyInfo = 'myInfo'; //我的资料页面
    const Render_TransactionRecords = 'tansactionRecords';  //交易记录页面

    public function onShowUserInfo() {
        if (yii::app()->request->isAjaxRequest) {
            $this->updateControl->addRenderView(self::Render_Display_UserInfo);
        } else {
            $this->updateControl->addRenderView(self::Render_Display_UserInfo);
        }
    }

    public function onShowApproveMember() {
        if (yii::app()->request->isAjaxRequest) {
            $this->updateControl->addRenderView(self::Render_Approve_Membership);
        } else {
            $this->updateControl->addRenderView(self::Render_Approve_Membership);
        }
    }

    public function onShowAssignRoleToUser() {
        
    }

    public function onShowAuthenticate() {
        if (yii::app()->request->isAjaxRequest) {
            $this->updateControl->addRenderView(self::Render_Authenticate_User);
        } else {
            $this->updateControl->addRenderView(self::Render_Authenticate_User);
        }
    }

    public function onShowAuthenticateHamshun() {
        $user = Blyn::app()->getCurrentUser();
        $userInfo = $user->getAttribute('userInfo');
        $isAuthenticateHamshun = 'no';
        $attributes = array();
        if ($userInfo) {
            $attributes = $userInfo->getChildren();
            foreach ($attributes as $attr) {
                if ($attr->getName() == 'isAuthenticateHamshun') {
                    $isAuthenticateHamshun = $attr->getValue();
                }
            }
        }
        if ($isAuthenticateHamshun == 'yes') {
            $this->updateControl->addRenderView('displayUserInfo_hamshun');
        } else {
            $this->updateControl->addRenderView(self::Render_Authenticate_User_hamshun);
        }
//        if (yii::app()->request->isAjaxRequest) {
//            $this->updateControl->addRenderView(self::Render_Authenticate_User_hamshun);
//        } else {
//            $this->updateControl->addRenderView(self::Render_Authenticate_User_hamshun);
//        }
    }

    public function onModifyUserInfo() {
        if (yii::app()->request->isAjaxRequest) {
            $this->updateControl->addRenderView(self::Render_Modify_UserInfo);
        } else {
            $this->updateControl->addRenderView(self::Render_Modify_UserInfo);
        }
    }

    public function onSaveUserInfo() {
        $activeLink = Blyn::app()->getUIManager()->getActiveLink();
        $postManager = new BPostManager();
        $postData = $postManager->parsedModelData();
        $mediaList = $postManager->populateMediaListFromPostData($postData, 'userInfo');
        $user = Blyn::app()->getCurrentUser();
        $data = array();
        $userInfoTable = new BUserSheet('userinfo');
        $userInfoItem = $userInfoTable->getList(array('userId' => $user->getId()));

        if ($userInfoItem) {
            $emailMedia = $mediaList['email'];
            if ($emailMedia) {
                unset($mediaList['email']);
                $data['email'] = $emailMedia->content;
                $userInfoItem->addItem('email', $data['email']);
                //$user->email = $emailMedia->content;
            }

            $userNameMedia = $mediaList['userName'];
            if ($userNameMedia) {
                unset($mediaList['userName']);
                $data['userName'] = $userNameMedia->content;
                $userInfoItem->addItem('userName', $data['userName']);
                //$user->userName = $userNameMedia->content;
            }

            $userIdMedia = $mediaList['userId'];
            if ($userIdMedia) {
                unset($mediaList['userId']);
                $data['userId'] = $userIdMedia->content;
                $userInfoItem->addItem('loginId', $data['userId']);
            }
        }
        //$user->userId = $userIdMedia->content;
        $user->save($data);
        foreach ($mediaList as $key => $media) {
            $user->addAttribute('userInfo.' . $key, $media->content);
            if ($userInfoItem) {
                $userInfoItem->addItem($key, $media->content);
            }
        }

        $this->updateControl->addRenderView(self::Render_Display_UserInfo);
    }

    public function onAuthenticateUserHamshun() {
        $postManager = new BPostManager();
        $postData = $postManager->parsedModelData();
        $mediaList = $postManager->populateMediaListFromPostData($postData, 'userInfo');
        $user = Blyn::app()->getCurrentUser();
        $data = array();
        //采集信息
        $name = $mediaList['userName']->content;
        $useridcard = $mediaList['useridcard']->content;
        $openid = $mediaList['openid']->content;
//        $openid="oxmO-uNBCGBjzWouLnH44JrmutiA";
        //验证
        $url = "http://210.209.93.90:8012/WechatAuthentication/WechatAuthenticationx?username=" . $name . "&useridcard=" . $useridcard;
        $weixin = new BWeChatClass("wxd33a8d04590d6e58", "de068491fd6a4f42f122c7d2f10208b2");
        $res = $weixin->https_request($url);
//        $res = "success,周廷勇,13896724130,512323197902140091,6228480470661827712";
        if ($res != "false") {
            $return_arr = explode(',', $res);
            $resStr = $return_arr[0];
            if ($resStr == 'success') {
                //与后台验证成功
                $message = '尊敬的用户，您已经成功认证个人信息！感谢您的配合。';
                $type = 'text';
                $send_err = $weixin->send_custom_message($openid, $type, $message);
                $send_res = json_decode($send_err, true);
                if ($send_res["errmsg"] == "ok") {
                    //发送消息成功
                    $userNameMedia = $mediaList['userName'];
                    unset($mediaList['userName']);
                    $data['userName'] = $userNameMedia->content;

                    $user->save($data);
                    foreach ($mediaList as $key => $media) {
                        $user->addAttribute('userInfo.' . $key, $media->content);
                    }

                    $user->addAttribute('userInfo.mobile', $return_arr[2]);
                    $user->addAttribute('userInfo.bankNum', $return_arr[4]);
                    $this->updateControl->addRenderView('displayUserInfo_hamshun');
                }
            }
        }
    }

    /* 展示会员卡首页 */

    public function onShowMemberCard() {
        $this->updateControl->addRenderView(self::Render_MemberCard);
    }

    /* 展示用户的余额页面 */

    public function onShowAccountBalance() {
        $this->updateControl->addRenderView(self::Render_AccountBalance);
    }

    /* 展示会员积分 */

    public function onShowMyPoint() {
        $this->updateControl->addRenderView(self::Render_MyPoint);
    }

    /* 展示会员信息 */

    public function onShowMyInfo() {
        $this->updateControl->addRenderView(self::Render_MyInfo);
    }

    /* 展示会员交易记录 */

    public function onShowTransactionRecords() {
        $this->updateControl->addRenderView(self::Render_TransactionRecords);
    }

    public function onShowSpaceUserRoleList() {
        $roleCooker = new BARoleCooker();
        $spaceRoleList = $roleCooker->getAllSpaceUserWithRole();
        $this->getUpdateControl()->addRenderView('spaceUserRoleList', 'space_user_role_list', array('spaceUserRoleList' => $spaceRoleList));
    }

    public function onShowAddUserRole() {
        $userId = $this->activeLink->getLinkVariable('userId');
        $roleCooker = new BARoleCooker();
        $userJoinableRoleData = array();
        $spaceRoles = BARoleCooker::getAllSpaceRoleData(NULL, 'objectList');
        $userRoles = BARoleCooker::getAllUserRoles(NULL, $userId);
        foreach ($spaceRoles as $id => $role) {
            if (!isset($userRoles[$id])) {
                $userJoinableRoleData[$id] = $role;
            }
        }
        $this->getUpdateControl()->addRenderView('addUserRole', 'addUserRole', array(
            'userId' => $userId,
            'userJoinableRoleData' => $userJoinableRoleData));
    }

    public function onAddUserRole() {

        $postData = $_POST['BDynamicFormModel'];

        $userId = $this->activeLink->getLinkVariable('userId');
        $user = new BUser($userId);

        $checkedRoleData = array();
        foreach ($postData as $key => $value) {
            $addRole = $value['addRole'];
            if ($addRole == 1) {
                $role = new BRole($key);
                $role->addMember($user);
            }
        }

        $this->onShowSpaceUserRoleList();
    }

}
